<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>

    <el-card class="box-card">
      <el-row :gutter="20">
        <el-col :span="8">
          <el-input
            v-model="usersList.query"
            placeholder="请输入内容"
            clearable
            @clear="renderUsers()"
            @keyup.enter.native="renderUsers()"
          >
            <el-button slot="append" icon="el-icon-search" @click="usersSearch"></el-button>
          </el-input>
        </el-col>
        <el-col :span="7">
          <el-button type="primary" @click="addDialog=true">添加用户</el-button>
        </el-col>
      </el-row>
      <el-table :data="tableData" border style="width: 100%">
        <el-table-column label="序号" width="50" type="index"></el-table-column>
        <el-table-column prop="username" label="用户名"></el-table-column>
        <el-table-column prop="mobile" label="手机号码" width="150"></el-table-column>
        <el-table-column prop="role_name" label="角色" width="180"></el-table-column>
        <el-table-column prop="email" label="邮箱" width="200"></el-table-column>
        <el-table-column prop="mg_state" label="状态" width="150">
          <el-switch
            slot-scope="strData"
            v-model="strData.row.mg_state"
            @change="stateChange(strData.row,strData.row.mg_state)"
          ></el-switch>
        </el-table-column>
        <el-table-column label="操作" width="180">
          <el-row slot-scope="strDate">
            <el-button
              type="primary"
              size="mini"
              icon="el-icon-edit"
              @click="showEditDialog(strDate.row)"
            ></el-button>
            <el-button
              type="danger"
              size="mini"
              icon="el-icon-delete"
              @click="usersDel(strDate.row.id)"
            ></el-button>
            <el-tooltip
              class="item"
              effect="dark"
              content="分配角色"
              placement="top"
              :enterable="false"
            >
              <el-button
                type="warning"
                size="mini"
                icon="el-icon-setting"
                @click="showRoleDailog(strDate.row)"
              ></el-button>
            </el-tooltip>
          </el-row>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="usersList.pagenum"
        :page-sizes="[2, 3, 5]"
        :page-size="usersList.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="tot"
      ></el-pagination>
    </el-card>

    <!-- Dialog添加弹框 -->
    <el-dialog
      title="添加用户"
      :visible.sync="addDialog"
      width="50%"
      @close="$refs.addFormRef.resetFields()"
    >
      <el-form :model="addForm" :rules="addFormRules" label-width="80px" ref="addFormRef">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addForm.username" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="addForm.password" autocomplete="off" show-password></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addForm.email" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="手机号码" prop="mobile">
          <el-input v-model="addForm.mobile" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="addDialog=false">取 消</el-button>
        <el-button type="primary" @click="addUsers()">确 定</el-button>
      </div>
    </el-dialog>

    <!-- Dialog修改弹窗 -->
    <el-dialog
      title="修改用户"
      :visible.sync="editDialog"
      width="50%"
      @close="editDialogReset($refs.editFormRef)"
    >
      <el-form :model="editForm" :rules="editFormRules" label-width="80px" ref="editFormRef">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="editForm.username" autocomplete="off" disabled></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editForm.email" autocomplete="off" clearable></el-input>
        </el-form-item>
        <el-form-item label="手机号码" prop="mobile">
          <el-input v-model="editForm.mobile" autocomplete="off" clearable></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="editDialog=false">取 消</el-button>
        <el-button type="primary" @click="editUser()">确 定</el-button>
      </div>
    </el-dialog>
    <!-- Dialog分配角色弹窗 -->
    <el-dialog
      title="用户分配角色"
      :visible.sync="setRoleDialog"
      width="50%"
      @close="$refs.setRoleRef.resetFields()"
    >
      <el-form :model="setRole" ref="setRoleRef" :rules="setRoleRules">
        <el-form-item label="当前的用户" prop="username">{{setRole.username}}</el-form-item>
        <el-form-item label="当前的角色" prop="role_name">{{setRole.role_name}}</el-form-item>
        <el-form-item label="分配新角色" prop="rid">
          <el-select
            v-model="setRole.rid"
            placeholder="请选择"
            ref="theRole"
            clearable
            @clear="$refs.setRoleRef.resetFields()"
          >
            <el-option
              v-for="item in roleList"
              :key="item.id"
              :label="item.roleName"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="setRoleDialog = false">取 消</el-button>
        <el-button type="primary" @click="fenrole()">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  created () {
    this.renderUsers()
  },
  methods: {
    usersSearch () {
      this.renderUsers()
    },
    handleSizeChange (newSize) {
      // console.log(newSize)
      this.usersList.pagesize = newSize
      this.renderUsers()
    },
    handleCurrentChange (newPage) {
      // console.log(newPage)
      this.usersList.pagenum = newPage
      this.renderUsers()
    },
    // 获得用户列表
    async renderUsers () {
      const { data: res } = await this.$http.get('users', {
        params: this.usersList
      })
      console.log('添加角色响应', res)
      this.tableData = res.data.users
      this.tot = res.data.total
    },
    async stateChange (user, state) {
      const { data: stateRes } = await this.$http.put(
        // 'users/' + user.id + '/state/' + state
        `users/${user.id}/state/${state}`
      )
      console.log(user)
      this.$message.success(stateRes.meta.msg)
      // this.renderUsers()
    },
    addUsers () {
      this.$refs.addFormRef.validate(async valid => {
        if (valid) {
          const { data: userRes } = await this.$http.post('users', this.addForm)
          console.log(userRes)
          this.addDialog = false
          this.$message.success(userRes.meta.msg)
          this.renderUsers()
        }
      })
    },
    usersDel (id) {
      this.$confirm('确定删除该用户吗?', '删除', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          // this.$message({
          //   type: 'success',
          //   message: id
          // })
          const { data: del } = await this.$http.delete('users/' + id)
          this.$message.success(del.meta.msg)
          if (this.usersList.pagenum !== 1 && this.tableData.length === 1) {
            this.usersList.pagenum--
            // console.log(this.tableData)
          }
          this.renderUsers()
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },

    // 显示角色分配弹框
    async showRoleDailog (user) {
      const { data: dt } = await this.$http.get('roles')
      console.log(dt.data)
      this.roleList = dt.data
      this.setRoleDialog = true
      this.setRole = user
    },

    // 收集角色存储入库
    fenrole () {
      // 校验
      this.$refs.setRoleRef.validate(async valid => {
        if (valid) {
          const { data: dt } = await this.$http.put(
            `users/${this.setRole.id}/role`,
            { rid: this.setRole.rid }
          )
          // console.log(dt)
          this.setRoleDialog = false
          this.$message.success(dt.meta.msg)
          this.renderUsers()
        }
      })
    },
    // 显示修改用户框
    showEditDialog (user) {
      this.editDialog = true
      this.editForm = user
    },
    // 收集修改信息内容
    editUser () {
      this.$refs.editFormRef.validate(async valid => {
        if (valid) {
          const { data: dt } = await this.$http.put(
            'users/' + this.editForm.id,
            this.editForm
          )
          console.log('修改信息响应', dt)
          this.$message.success(dt.meta.msg)
          this.editDialog = false
          this.renderUsers()
        }
      })
    },
    // 关闭初始化修改dialog框
    editDialogReset (form) {
      if (form) {
        form.resetFields()
        this.renderUsers()
      }
    }
  },
  watch: {
    'setRole.rid': function (newVal) {
      console.log('监听改变', newVal)
      if (this.$refs.theRole) {
        if (newVal) {
          console.log(this.$refs.theRole.$children[0].$refs.input)
          this.$refs.theRole.$children[0].$refs.input.style.borderColor =
            'lightgreen'
          // console.log(newVal)
        } else {
          this.$refs.theRole.$children[0].$refs.input.style.borderColor = ''
        }
      }
    }
  },
  data () {
    const checkMoblie = (rule, value, callback) => {
      const reg = /^1[3-9]\d{9}$/
      if (reg.test(value)) {
        callback()
      } else {
        return callback(new Error('手机号码格式错误'))
      }
    }
    return {
      tot: 0,
      tableData: [],
      usersList: {
        query: '',
        pagenum: 1,
        pagesize: 2
      },
      addDialog: false,
      addForm: {
        username: '',
        password: '',
        email: '',
        mobile: ''
      },
      addFormRules: {
        username: [{ required: true, message: '用户名必填', trigger: 'blur' }],
        password: [{ required: true, message: '密码必填', trigger: 'blur' }],
        email: [{ required: true, message: '邮箱必填', trigger: 'blur' }],
        mobile: [{ validator: checkMoblie, trigger: 'blur' }]
      },

      // 角色分配
      setRole: {
        username: '',
        role_name: '',
        rid: ''
      },

      roleList: [],
      setRoleDialog: false,

      // 角色分配表单校验
      setRoleRules: {
        rid: [
          { required: true, message: '必须选取一个角色', trigger: 'change' }
        ]
      },

      // 修改用户信息
      editDialog: false,
      // 修改用户信息表单
      editForm: {
        username: '',
        email: '',
        mobile: ''
      },
      // 修改用户表单校验
      editFormRules: {
        mobile: [{ required: true, message: '手机号必填', trigger: 'blur' }]
      }
    }
  }
}
</script>

<style lang="less" scoped>
</style>
